﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Configuration;
using System.Threading.Tasks;
using Entities;

namespace Sales.Business.BO
{
    public class BOBase<T> where T : class
    {
        private String webAPIUrl;
        protected String APIName;

        public BOBase()
        {
            webAPIUrl = ConfigurationSettings.AppSettings["WebAPIUrl"];
        }

        protected HttpClient GetClient()
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(webAPIUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            return client;
        }

        public void Add(T item)
        {
           HttpClient client = GetClient();
           HttpResponseMessage response = client.PostAsJsonAsync(APIName, item).Result;
           client.Dispose();
        }

        public void Update(int id, T item)
        {
            HttpClient client = GetClient();
            HttpResponseMessage response = client.PutAsJsonAsync(APIName + "/" + id, item).Result;
            client.Dispose();
        }

        public void Remove(int id)
        {
            HttpClient client = GetClient();
            HttpResponseMessage response = client.DeleteAsync(APIName + "/" + id).Result;
            client.Dispose();
        }

        public IEnumerable<T> GetAll()
        {
            HttpClient client = GetClient();
            HttpResponseMessage response = client.GetAsync(APIName).Result;
            if (response.IsSuccessStatusCode)
            {
                IEnumerable<T> items = response.Content.ReadAsAsync<IEnumerable<T>>().Result;
                client.Dispose();
                return items;
            }
            client.Dispose();
            return null;
        }

        public T GetItemByID(int id)
        {
            HttpClient client = GetClient();
            HttpResponseMessage response = client.GetAsync(APIName + "/" + id).Result;
            if (response.IsSuccessStatusCode)
            {
                T item = response.Content.ReadAsAsync<T>().Result;
                client.Dispose();
                return item;
            }
            client.Dispose();
            return null;
        }
    }
}
